package com.sum.tea.xinlian

/**
 * 连接页面类 若demo以及集成了该平台的供电管理。可以从列表中选中相关平台，则自动
 * 会列出其串口地址。并且上电后连接读写器。若无该平台则手动输入地址，ip地址或者串口地址
 *
 * @author Administrator
 */
import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.lifecycle.Observer
import com.pow.api.cls.RfidPower
import com.pow.api.cls.RfidPower.PDATYPE
import com.power.OtherPower
import com.sum.common.base.BaseMvvmActivity
import com.sum.tea.R
import com.sum.tea.contants.AppConfig
import com.sum.tea.databinding.ActivityTab1TablelayoutConnectBinding
import com.sum.tea.xinlian.viewmodel.Sub1TabViewModel

class Sub1TabActivity : BaseMvvmActivity<ActivityTab1TablelayoutConnectBinding, Sub1TabViewModel>()  {

    private lateinit var myapp:AppConfig
    override fun initView(savedInstanceState: Bundle?) {
        val antPortAdapter = ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            mViewModel.antPorts
        ).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }
        mBinding.spinnerAntports.adapter = antPortAdapter

        val pdaTypeAdapter = ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            mViewModel.pdaTypes
        ).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }
        mBinding.spinnerPdatype.adapter = pdaTypeAdapter

        val baudRateAdapter = ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            mViewModel.baudRates
        ).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }
        mBinding.spinnerCcbaudrate.adapter = baudRateAdapter
        mBinding.spinnerCcbaudrate.setSelection(5) // 默认选择115200

        // 恢复保存的状态
        myapp = mViewModel.getAppConfig()
        val spf = myapp.spf
        val pdatypestr = myapp.spf.GetString("PDATYPE")
        val addressstr = myapp.spf.GetString("ADDRESS")
        val antportstr = myapp.spf.GetString("ANTPORT")
        val baudratstr = myapp.spf.GetString("BAUDRATE")
        if(mViewModel.isotherpowerup){
            mBinding.editTextAdr.setText(OtherPower.OpAddr)
            OtherPower.Ctt = this.applicationContext
        }else{
            if (pdatypestr != "") {
                mBinding.spinnerPdatype.setSelection(pdatypestr.toInt())
                if (mBinding.spinnerPdatype.selectedItemPosition == 0) {
                    mBinding.editTextAdr.setText(addressstr)
                }
            }
        }
        if (antportstr != "") {
            mBinding.spinnerAntports.setSelection(antportstr.toInt())
        }
        val baudRate = spf.GetString("BAUDRATE") ?: "115200"
        val baudIndex = mViewModel.baudRates.indexOf(baudRate).takeIf { it != -1 } ?: 5
        mBinding.spinnerCcbaudrate.setSelection(baudIndex)

        // 使用高阶函数设置按钮点击事件
        mBinding.buttonConnect.setOnClickListener {
            val ip = mBinding.editTextAdr.text.toString()
            val selectedPdaType = mBinding.spinnerPdatype.selectedItemPosition
            val selectedAntPort = mBinding.spinnerAntports.selectedItemPosition
            val selectedBaudRate = mBinding.spinnerCcbaudrate.selectedItem.toString()

            mViewModel.connectReader(
                ip,
                selectedPdaType,
                selectedAntPort,
                selectedBaudRate
            )
        }

        mBinding.buttonDisconnect.setOnClickListener {
            mViewModel.disconnectReader()
        }

        mBinding.buttonMenu.setOnClickListener {
            openOptionsMenu()
        }

        // Spinner选中监听
        mBinding.spinnerPdatype.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?, view: View?, position: Int, id: Long
            ) {
                val pdaType = PDATYPE.valueOf(position)
                myapp.Rpower = RfidPower(pdaType, applicationContext)
                Log.d("spinnerPdatype","spinnerPdatype pdaType:$pdaType")
                if (pdaType != PDATYPE.NONE) {
                    mBinding.editTextAdr.setText(myapp.Rpower.GetDevPath())
                }

                // 显示设备型号和CPU ABI
                val mod = "${android.os.Build.MODEL} ${android.os.Build.CPU_ABI}"
                Toast.makeText(this@Sub1TabActivity, mod, Toast.LENGTH_SHORT).show()
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }

        // 观察ViewModel的LiveData以更新UI
        mViewModel.isConnected.observe(this, Observer { isConnected ->
            mBinding.buttonConnect.isEnabled = !isConnected
            mBinding.buttonDisconnect.isEnabled = isConnected
        })

        mViewModel.tabsVisible.observe(this) { visible ->
            val tabHost = AppConfig.getInstance().tabHost
            val tabWidget = tabHost.tabWidget
            val visibility = if (visible) View.VISIBLE else View.INVISIBLE
            // 假设有至少4个标签页（索引0-3）
            if (tabWidget.childCount > 1) tabWidget.getChildAt(1).visibility = visibility
            if (tabWidget.childCount > 2) tabWidget.getChildAt(2).visibility = visibility
            if (tabWidget.childCount > 3) tabWidget.getChildAt(3).visibility = visibility
            if (visible) {
                tabHost.setCurrentTab(1)
            }
        }

        mViewModel.moduleInfo.observe(this, Observer { info ->
            mBinding.textViewModule.text = info
        })

        mViewModel.toastMessage.observe(this) { message ->
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        }

        // 隐藏键盘
        hideKeyboard()
    }

    private fun hideKeyboard() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        currentFocus?.let { view ->
            imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event?.action == KeyEvent.ACTION_DOWN) {
            val currentTime = System.currentTimeMillis()
            val appConfig = mViewModel.getAppConfig()
            if ((currentTime - appConfig.exittime) > 2000) {
                Toast.makeText(this, getString(R.string.Constr_Putandexit), Toast.LENGTH_SHORT).show()
                appConfig.exittime = currentTime
            } else {
                finish()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun openOptionsMenu() {
        val config = resources.configuration
        if ((config.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK) > Configuration.SCREENLAYOUT_SIZE_LARGE) {
            val originalScreenLayout = config.screenLayout
            config.screenLayout = Configuration.SCREENLAYOUT_SIZE_LARGE
            super.openOptionsMenu()
            config.screenLayout = originalScreenLayout
        } else {
            super.openOptionsMenu()
        }
    }
}

